<template>
  <div class="main-layout">
    <el-container class="layout-container">
      <!-- 顶部导航栏 -->
      <el-header class="layout-header">
        <div class="header-content">
          <div class="logo">
            <!-- 使用全局配置的logo -->
            <img :src="configStore.getLogoUrl" :alt="configStore.getLogo.alt" :title="configStore.getLogo.title" class="logo-image" />
            <span class="logo-text">{{ configStore.getAppName }}</span>
          </div>
          <div class="header-center">
            <!-- 天气和位置显示 -->
            <div class="weather-location" v-loading="weatherLoading">
              <div class="location-info" v-if="locationInfo.city">
                <el-icon><Location /></el-icon>
                <span>{{ locationInfo.city }}</span>
              </div>
              <div class="weather-info" v-if="weatherInfo.temp">
                <el-icon><Sunny v-if="weatherInfo.icon === 'sunny'" /><Cloudy v-else-if="weatherInfo.icon === 'cloudy'" /><PartlyCloudy v-else /></el-icon>
                <span class="weather-temp">{{ weatherInfo.temp }}°C</span>
                <span class="weather-desc">{{ weatherInfo.desc }}</span>
              </div>
              <el-button 
                v-if="!locationInfo.city" 
                type="text" 
                size="small" 
                @click="getLocation"
                :loading="locationLoading"
              >
                <el-icon><LocationFilled /></el-icon>
                获取位置
              </el-button>
            </div>
            
            <!-- 搜索框 -->
            <div class="header-search">
              <el-input
                v-model="searchText"
                placeholder="搜索文件、内容..."
                class="search-input"
                clearable
                @focus="handleSearchFocus"
                @blur="handleSearchBlur"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>
          <div class="header-right">
            <div class="user-info" v-if="userInfo">
              <el-dropdown @command="handleCommand">
                <span class="user-dropdown">
                  <el-icon><User /></el-icon>
                  <span>{{ userInfo?.nickname || userInfo?.username || '用户' }}</span>
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="admin" v-if="isAdmin">
                      <el-icon><Setting /></el-icon>
                      后台管理
                    </el-dropdown-item>
                    <el-dropdown-item command="logout">
                      <el-icon><SwitchButton /></el-icon>
                      退出登录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="user-info" v-else>
              <el-button type="text" @click="router.push('/login')">
                <el-icon><User /></el-icon>
                登录
              </el-button>
            </div>
          </div>
        </div>
      </el-header>
      
      <el-container class="main-content">
        <!-- 左侧导航栏 -->
        <el-aside width="200px" class="layout-aside">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            router
            background-color="#304156"
            text-color="#bfcbd9"
            active-text-color="#409eff"
          >
            <el-menu-item index="/home">
              <el-icon><House /></el-icon>
              <span>首页</span>
            </el-menu-item>
            <el-menu-item index="/module1">
              <el-icon><Grid /></el-icon>
              <span>模块一</span>
            </el-menu-item>
            <el-menu-item index="/module2">
              <el-icon><DataAnalysis /></el-icon>
              <span>模块二</span>
            </el-menu-item>
            <el-menu-item index="/module3">
              <el-icon><Tools /></el-icon>
              <span>模块三</span>
            </el-menu-item>
            <el-menu-item index="/module4">
              <el-icon><Document /></el-icon>
              <span>模块四</span>
            </el-menu-item>
            <el-menu-item index="/module5">
              <el-icon><Sunny /></el-icon>
              <span>天气查询系统</span>
            </el-menu-item>
            <el-menu-item index="/ai">
              <el-icon><MagicStick /></el-icon>
              <span>AI 智能助手</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <!-- 主内容区 -->
        <el-main class="layout-main">
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { useConfigStore } from '../store/configStore'

// 使用配置状态管理
const configStore = useConfigStore()
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  FolderOpened, User, Setting, SwitchButton, House,
  Grid, DataAnalysis, Tools, Document, Collection, MagicStick,
  Location, LocationFilled, Sunny, Cloudy, PartlyCloudy, Search
} from '@element-plus/icons-vue'
import { userApi } from '@/api'

const router = useRouter()
const route = useRoute()

const userInfo = ref(null)
const isAdmin = ref(false)
const activeMenu = computed(() => route.path)

// 天气和位置相关
const locationInfo = ref({
  city: '',
  province: '',
  district: ''
})
const weatherInfo = ref({
  temp: '',
  desc: '',
  icon: 'sunny'
})
const weatherLoading = ref(false)
const locationLoading = ref(false)
const searchText = ref('')

onMounted(async () => {
  // 可选：尝试获取用户信息，但不强制登录
  await checkLogin()
  // 获取位置和天气信息
  await getLocation()
})

const checkLogin = async () => {
  try {
    const res = await userApi.checkLogin()
    if (res.data?.isLogin) {
      userInfo.value = {
        username: res.data.username,
        nickname: res.data.nickname
      }
      isAdmin.value = res.data.isAdmin
    }
  } catch (error) {
    // 忽略错误，不强制登录
    console.log('未登录或登录已过期')
  }
}


const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (userInfo.value) {
        try {
          await userApi.logout()
        } catch (e) {
          // 忽略登出错误
        }
      }
      localStorage.removeItem('军神网盘-token')
      userInfo.value = null
      isAdmin.value = false
      ElMessage.success('退出成功')
    } catch (error) {
      // 用户取消
    }
  } else if (command === 'admin') {
    router.push('/admin/storage')
  }
}

// 获取位置信息
const getLocation = async () => {
  if (!navigator.geolocation) {
    ElMessage.warning('您的浏览器不支持地理位置定位')
    return
  }
  
  locationLoading.value = true
  try {
    // 使用浏览器定位API
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        const { latitude, longitude } = position.coords
        // 通过逆地理编码获取城市信息
        await getCityByCoordinates(latitude, longitude)
        // 获取天气信息
        await getWeather(latitude, longitude)
        locationLoading.value = false
      },
      async (error) => {
        console.error('获取位置失败:', error)
        // 如果定位失败，使用默认城市（北京）
        await getDefaultLocation()
        locationLoading.value = false
      },
      {
        enableHighAccuracy: false,
        timeout: 5000,
        maximumAge: 300000 // 5分钟缓存
      }
    )
  } catch (error) {
    console.error('定位错误:', error)
    await getDefaultLocation()
    locationLoading.value = false
  }
}

// 通过坐标获取城市信息（使用免费API）
const getCityByCoordinates = async (lat, lon) => {
  try {
    // 使用高德地图逆地理编码API（需要申请key，这里使用示例）
    // 或者使用其他免费API如：https://api.bigdatacloud.net/data/reverse-geocode-client
    const response = await fetch(
      `https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${lat}&longitude=${lon}&localityLanguage=zh`
    )
    const data = await response.json()
    
    if (data.locality) {
      locationInfo.value = {
        city: data.locality || data.city || '未知',
        province: data.principalSubdivision || '',
        district: data.localityInfo?.administrative?.[0]?.name || ''
      }
    }
  } catch (error) {
    console.error('获取城市信息失败:', error)
    // 使用默认值
    locationInfo.value = {
      city: '北京',
      province: '北京市',
      district: ''
    }
  }
}

// 获取默认位置
const getDefaultLocation = async () => {
  locationInfo.value = {
    city: '北京',
    province: '北京市',
    district: ''
  }
  // 使用北京的坐标获取天气
  await getWeather(39.9042, 116.4074)
}

// 获取天气信息（使用OpenWeatherMap免费API，需要注册获取API Key）
const getWeather = async (lat, lon) => {
  weatherLoading.value = true
  try {
    // 注意：这里使用示例API，实际使用时需要：
    // 1. 注册 OpenWeatherMap (https://openweathermap.org/api) 获取API Key
    // 2. 或者使用其他免费天气API，如和风天气、心知天气等
    // 3. 或者使用后端代理API避免跨域问题
    
    // 示例：使用OpenWeatherMap API（需要替换YOUR_API_KEY）
    const apiKey = 'YOUR_API_KEY' // 请替换为实际的API Key
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric&lang=zh_cn`
    
    // 如果API Key未配置，使用模拟数据
    if (apiKey === 'YOUR_API_KEY') {
      // 模拟天气数据
      setTimeout(() => {
        weatherInfo.value = {
          temp: '22',
          desc: '晴朗',
          icon: 'sunny'
        }
        weatherLoading.value = false
      }, 500)
      return
    }
    
    const response = await fetch(url)
    const data = await response.json()
    
    if (data.main) {
      weatherInfo.value = {
        temp: Math.round(data.main.temp),
        desc: data.weather[0]?.description || '未知',
        icon: getWeatherIcon(data.weather[0]?.main)
      }
    }
  } catch (error) {
    console.error('获取天气失败:', error)
    // 使用默认天气数据
    weatherInfo.value = {
      temp: '22',
      desc: '晴朗',
      icon: 'sunny'
    }
  } finally {
    weatherLoading.value = false
  }
}

// 根据天气代码获取图标类型
const getWeatherIcon = (weatherMain) => {
  const iconMap = {
    'Clear': 'sunny',
    'Clouds': 'cloudy',
    'Rain': 'cloudy',
    'Drizzle': 'cloudy',
    'Thunderstorm': 'cloudy',
    'Snow': 'cloudy',
    'Mist': 'cloudy',
    'Fog': 'cloudy'
  }
  return iconMap[weatherMain] || 'sunny'
}

// 搜索相关方法
const handleSearchFocus = () => {
  // 搜索框获得焦点时的处理（可选）
}

const handleSearchBlur = () => {
  // 搜索框失去焦点时的处理（可选）
}

const handleSearch = () => {
  // 按回车键搜索时的处理（可选）
  if (searchText.value.trim()) {
    console.log('搜索内容:', searchText.value)
    // 这里可以添加搜索逻辑
  }
}
</script>

<style lang="scss" scoped>
.main-layout {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.layout-container {
  height: 100%;
}

.layout-header {
  height: 60px;
  padding: 0;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  gap: 20px;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.weather-location {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 0 16px;
  border-radius: 6px;
  background: #f5f7fa;
  
  .location-info {
    display: flex;
    align-items: center;
    gap: 6px;
    color: #606266;
    font-size: 14px;
    
    .el-icon {
      color: #409eff;
      font-size: 16px;
    }
  }
  
  .weather-info {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #606266;
    font-size: 14px;
    
    .el-icon {
      font-size: 18px;
      color: #f39c12;
    }
    
    .weather-temp {
      font-weight: 600;
      color: #303133;
    }
    
    .weather-desc {
      color: #909399;
      font-size: 12px;
    }
  }
}

.header-search {
  min-width: 300px;
  max-width: 500px;
  flex: 1;
  
  .search-input {
    :deep(.el-input__wrapper) {
      border-radius: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      transition: all 0.3s;
      
      &:hover {
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
      }
      
      &.is-focus {
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
      }
    }
    
    :deep(.el-input__inner) {
      padding-left: 12px;
    }
    
    :deep(.el-input__prefix) {
      left: 12px;
      color: #909399;
    }
  }
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
}

.logo-image {
  width: 28px;
  height: 28px;
  border-radius: 4px;
  vertical-align: middle;
  font-weight: bold;
  color: #409eff;
  
  .el-icon {
    font-size: 24px;
  }
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-menu {
  border: none;
}

.user-info {
  .user-dropdown {
    display: flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 4px;
    transition: background-color 0.3s;
    
    &:hover {
      background-color: #f5f7fa;
    }
  }
}

.main-content {
  height: calc(100vh - 60px);
  overflow: hidden;
}

.layout-aside {
  background-color: #304156;
  overflow: hidden;
}

.sidebar-menu {
  border: none;
  height: 100%;
  overflow-y: auto;
}

.layout-main {
  padding: 20px;
  background: #f5f7fa;
  overflow-y: auto;
}
</style>

